#include <stdio.h>
#include <esp_system.h>
#include <esp_log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <nvs.h>
#include <nvs_flash.h>
#include "device/device.h"
#include "nvs/value.h"

void app_main(void)
{
    // log device info
    log_esp_info();

    // Initialize NVS
    ESP_LOGI("ESP", "initialize NVS\n");
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        // NVS partition was truncated and needs to be erased
        // Retry nvs_flash_init
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);

    // Open
    printf("\n");
    printf("Opening Non-Volatile Storage (NVS) handle... \n");
    nvs_handle_t nvs_handle;
    err = nvs_open("storage", NVS_READWRITE, &nvs_handle);
    if (err != ESP_OK)
    {
        printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
        return;
    } else {
        printf("NVS Done\n");
    }

    //char *ssid = "Codemao-Office";
    //char *password = "2<3]OzU(!h";

    //write_wifi_info(nvs_handle, ssid, password);
    read_wifi_info(nvs_handle);
    // Close NVS
    nvs_close(nvs_handle);

    // Restart module
    for (int i = 100; i >= 0; i--)
    {
        ESP_LOGI("ESP", "Restarting in %d seconds...\n", i);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
    ESP_LOGI("ESP", "Restarting now.\n");
    fflush(stdout);
    esp_restart();
}
